﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iTunesFastForward.Lyrics;
using iTunesLib;
using System.Net;

namespace iTunesFastForward.Forms
{
    public partial class LyricsForm : Form
    {
        iTunesFastForwardForm _form;
        LyricsManager _lyricsManager;
        IITTrack _playingTrack;

        public bool AjaxLoadVisible
        {
            get { return ajaxLoadPictureBox.Visible; }
            set { ajaxLoadPictureBox.Visible = value; }
        }

        public IITTrack PlayingTrack
        {
            get { return _playingTrack; }
            set
            {
                _playingTrack = value;

                if (value != null)
                {
                    LyricsDesignation d = new LyricsDesignation
                    {
                        Album = value.Album,
                        Artist = value.Artist,
                        Song = value.Name
                    };
                    //artistLabel.Text = value.Artist;
                    //songLabel.Text = value.Name;

                    //artworkPictureBox.Image = _form.GetArtworkAsImage(value);

                    //providerComboBox.SelectedIndex = -1;

                    if (lyricBackgroundWorker.IsBusy)
                        lyricBackgroundWorker.CancelAsync();

                    LyricsDesignation d2 = _lyricsManager.GetLyrics(value);
                    if (d2 != null)
                        d.Lyrics = d2.Lyrics;

                    SetLyrics(d, true);
                }
            }
        }

        public LyricsForm(iTunesFastForwardForm form, LyricsManager lyricsManager)
        {
            _form = form;
            _lyricsManager = lyricsManager;

            InitializeComponent();
            if (iTFFSettings.Instance.LyricsFormPointLocation == null)
            {
                iTFFSettings.Instance.LyricsFormPointLocation = new Point(
                    Screen.GetWorkingArea(this).Right - this.Width - 10,
                    (int) Screen.GetWorkingArea(this).Height / 2 - this.Height / 2);
            }

            this.DataBindings.Add("Location", iTFFSettings.Instance, "LyricsFormPointLocation");

            try
            {
                foreach (var item in _lyricsManager.Providers)
                    providerComboBox.Items.Add(item);
            }
            catch (ApplicationException e)
            {   
                Utils.ShowErrorMessage(e.Message, "Error");
            }

            CheckPreviousAndNextButton();
        }

        public void SetLyrics(LyricsDesignation d, bool resetProviderSelection)
        {
            if (d == null)
                return;

            this.Text = string.Format("Lyrics: {0} - {1}", d.Artist, d.Song);
            artistLabel.Text = d.Artist;
            songLabel.Text = d.Song;
            lyricsTextBox.Text = d.Lyrics;
            lyricsTextBox.Select(0, 0);

            if (resetProviderSelection)
            {
                providerComboBox.SelectedIndex = -1;
                CheckPreviousAndNextButton();
            }

            if (!iTunesActions.Instance.COMCallDisabled)
            {
                artworkPictureBox.Image = _form.GetArtworkAsImage(iTunesActions.Instance.PlayingTrack);
            }
        }

        private void LyricsForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                e.Handled = true;
                e.SuppressKeyPress = true;
                this.Close();
            }
        }

        private void LyricsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Visible = false;
                this.WindowState = FormWindowState.Minimized;
            }

            iTFFSettings.Instance.LyricsFormPointLocation = Location;
        }

        private void previousButton_Click(object sender, EventArgs e)
        {
            providerComboBox.SelectedIndex -= 1;
            CheckPreviousAndNextButton();
        }

        private void nextButton_Click(object sender, EventArgs e)
        {
            providerComboBox.SelectedIndex += 1;
            CheckPreviousAndNextButton();
        }

        private void CheckPreviousAndNextButton()
        {
            if (providerComboBox.SelectedIndex <= 0)
                previousButton.Enabled = false;
            else
                previousButton.Enabled = true;
            if (providerComboBox.SelectedIndex >= providerComboBox.Items.Count - 1)
                nextButton.Enabled = false;
            else
                nextButton.Enabled = true;
        }

        private void validateButton_Click(object sender, EventArgs e)
        {
            if (!iTunesActions.Instance.COMCallDisabled)
            {
                _lyricsManager.SaveLyrics(iTunesActions.Instance.PlayingTrack, true, lyricsTextBox.Text); // protégé
            }
        }

        private void removeButton_Click(object sender, EventArgs e)
        {
            if (!iTunesActions.Instance.COMCallDisabled)
            {
                _lyricsManager.RemoveLyrics(iTunesActions.Instance.PlayingTrack); // protégé
                lyricsTextBox.Text = null;
            }
        }

        private LyricsProvider _selectedProvider;
        public void FetchLyrics()
        {
            if (!iTunesActions.Instance.COMCallDisabled)
            {
                if (lyricBackgroundWorker.IsBusy)
                    MessageBox.Show("Please wait, the application is currently searching for lyrics.", "Please wait", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    _selectedProvider = (LyricsProvider)providerComboBox.SelectedItem;
                    ajaxLoadPictureBox.Visible = true;
                    lyricBackgroundWorker.RunWorkerAsync(iTunesActions.Instance.PlayingTrack); // protégé
                }
            }
        }

        private void lyricBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = _lyricsManager.FetchLyrics((IITTrack)e.Argument, _selectedProvider);
        }

        private void lyricBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ajaxLoadPictureBox.Visible = false;

            if (e.Cancelled)
                return;

            if (e.Error != null)
            {
                var d = (LyricsDesignation)e.Result;
                if (d == null)
                {
                    lyricsTextBox.Text = "No lyrics found";
                    lyricsTextBox.Select(0, 0);
                }
                else
                    SetLyrics(d, false);
            }
            else
            {
                lyricsTextBox.Text = "Error raised. Check your internet connection";
                lyricsTextBox.Select(0, 0);
            }
            
        }

        public void GetLyrics(IITTrack t)
        {
            LyricsDesignation d = _lyricsManager.GetLyrics(t);
            if (d != null)
            {
                lyricsTextBox.Text = "No lyrics found";
                lyricsTextBox.Select(0, 0);
            }
            else
                SetLyrics(d, false);
        }

        private void providerComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (providerComboBox.SelectedIndex != -1)
                FetchLyrics();

            CheckPreviousAndNextButton();
        }
    }
}
